package com.devilvan.jsoup;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CrawlUtil {
    public static String parseTranslation(String resultJson){
        JSONArray jsonArray = JSON.parseArray(resultJson);
        JSONArray jsonArray1 = (JSONArray) jsonArray.get(0);
        JSONArray jsonArray2 = (JSONArray) jsonArray1.get(0);
        return jsonArray2.get(0)+"";
    }

    public static String googleTranslate(String langFrom, String langTo, String word) throws InterruptedException {
        StringBuffer response = null;
        while (true) {
            try {
                String url = "https://translate.googleapis.com/translate_a/single?" +
                        "client=gtx&" +
                        "sl=" + langFrom +
                        "&tl=" + langTo +
                        "&dt=t&q=" + URLEncoder.encode(word, "UTF-8");
                URL obj = new URL(url);
                HttpURLConnection con = (HttpURLConnection) obj.openConnection();
                con.setRequestProperty("User-Agent", "Mozilla/5.0");
                con.setRequestProperty("Content-Type", "application/json; utf-8");
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(con.getInputStream()));
                String inputLine;
                response = new StringBuffer();
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
                return parseTranslation(response.toString());
            } catch (IOException e) {
//                TimeUnit.MILLISECONDS.sleep(450);
                e.printStackTrace();
            }
        }
    }

    public static String matchRegularExp(String content, String pattern) {
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(content);
        if (m.find()) {
            m.reset();
            while (m.find()) {
                return m.group(0);
            }
        }
        return null;
    }

    public static void writeLine(OutputStreamWriter writer, String title, List<String> values) {
        try {
            if (EmptyUtil.isEmpty(title)) System.out.println("标题为空");
            if (EmptyUtil.isEmpty(values)) System.out.println("内容为空");
            if (!title.endsWith(":") && !title.endsWith("：")) title += "：";
            StringBuffer sb = new StringBuffer();
            for (String value : values) {
                sb.append(value).append(",");
            }
            String substring = sb.toString().substring(0, sb.length() - 1);
            writer.write(title + substring + "\r\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void writeLine(OutputStreamWriter writer, String title, String value) {
        try {
            if (EmptyUtil.isEmpty(title)) System.out.println("标题为空");
            if (EmptyUtil.isEmpty(value)) System.out.println("内容为空");
            if (!title.endsWith(":") && !title.endsWith("：")) title += "：";
            writer.write(title + value + "\r\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void writeSplitLine(OutputStreamWriter writer) {
        try {
            writer.write("-------------------------------------------------" + "\r\n");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Element getBodyElement(String targetUrl, Map<String, String> crawlConnectHeader) throws
            InterruptedException {
        Connection connect = Jsoup.connect(targetUrl);
        connect.header("Accept", crawlConnectHeader.get("Accept"));
        connect.header("Accept-Encoding", crawlConnectHeader.get("Accept-Encoding"));
        connect.header("Connection", crawlConnectHeader.get("Connection"));
        connect.header("Cookie", crawlConnectHeader.get("Cookie"));
        connect.header("Host",crawlConnectHeader.get("Host"));
        connect.header("User-Agent", crawlConnectHeader.get("User-Agent"));
        while (true) {
            try {
                return connect.get().body();
            } catch (IOException e) {
                TimeUnit.MILLISECONDS.sleep(300);
//                e.printStackTrace();
            }
        }
    }

    public static void setProxy() {
        System.getProperties().setProperty("proxySet", "true");
        //用的代理服务器
        System.getProperties().setProperty("http.proxyHost", "192.168.1.4");
        //代理端口
        System.getProperties().setProperty("http.proxyPort", "8848");
    }
}
